package ch.ti.kmltomap;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.android.gms.maps.model.LatLng;

public class Coordinates {
	private List<Coordinate> coordinates = new ArrayList<Coordinate>();
	
	public Coordinates(String coordinates){
		this.coordinates = new ArrayList<Coordinate>();
		
		StringTokenizer tokenizer = new StringTokenizer(coordinates," ");
		
		while(tokenizer.hasMoreTokens()){
			String coordinateString = tokenizer.nextToken();
			Coordinate coordinate = new Coordinate();
			int count = Utility.countMatches(coordinateString, ",");
			if(count == 3){
				coordinate.hasAltitude = true;
				String regex = "([+-]?\\d*\\.\\d+)(?![-+0-9\\.])(,)([+-]?\\d*\\.\\d+)(?![-+0-9\\.])(,)([+-]?\\d*\\.\\d+)(?![-+0-9\\.])";
				Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
				Matcher m = p.matcher(coordinateString);
				if(m.find()){
					try{
						extractCoordinates(m, coordinate);
						coordinate.altitude = Float.parseFloat(m.group(5));
					}catch (Exception e) {
					}
				}
			}else if(count == 2){
				String regex = "([+-]?\\d*\\.\\d+)(?![-+0-9\\.])(,)([+-]?\\d*\\.\\d+)(?![-+0-9\\.])";
				Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
				Matcher m = p.matcher(coordinateString);
				if(m.find()){
					try{
						extractCoordinates(m, coordinate);
					}catch (Exception e) {
					}
				}
			}
			this.coordinates.add(coordinate);
		}
	}

	private void extractCoordinates(Matcher m, Coordinate coordinate) {
		float longitude = Float.parseFloat(m.group(1));
		if(longitude >= -180 && longitude <= 180)
			coordinate.longitude = longitude;
		
		float latitude = Float.parseFloat(m.group(3));
		if(latitude >= -90 && latitude <= 90){
			coordinate.latitude = latitude;
		}
	}

	public List<Coordinate> coordinates() {
		return coordinates;
	}
	
	public List<LatLng> coordinatesLatLngs(){
		List<LatLng> latLngList = new ArrayList<LatLng>();
		for (Coordinate coordinate : this.coordinates) {
			latLngList.add(coordinate.latLng());
		}
		return latLngList;
	}
}
